package com.longcai.controller.customer;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.longcai.bean.ApiResult;
import com.longcai.bean.RedisUtil;
import com.longcai.entity.customer.ClyjUser;
import com.longcai.mapper.customer.ClyjUserMapper;
import com.longcai.service.customer.CustomerService;
import com.longcai.util.OSSUtils;
import com.longcai.util.TokenUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.UUID;


/**
 * <p>
 * 用户信息表 前端控制器
 * </p>
 *
 * @author M
 * @since 2019-03-19
 */
@Controller
@RequestMapping("/clyjUser")
public class CustomerController {
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private ClyjUserMapper clyjUserMapper;
    @Autowired
    private CustomerService customerService;
    @Autowired
    private TokenUtils tokenUtils;
    @Autowired
    private RedisUtil redisUtil;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 用户注册
     *
     * @param params
     * @return
     */
    @RequestMapping(value = "/register")
    @ResponseBody
    public ApiResult customerRegister(@RequestBody JSONObject params, HttpServletRequest request) {
        String phone = params.getString("phone");
        String code = params.getString("code");
        String pwd = params.getString("pwd");
        String inviteCode = params.getString("inviteCode");
        ClyjUser clyjUser = new ClyjUser();
        //判断参数
        if (StringUtils.isEmpty(phone) && StringUtils.isEmpty(pwd)) {
            logger.error("手机号和密码为空++++++++", phone, pwd);
            return ApiResult.fail("用户名或密码为空");
        }
        if (!code.equals("12345")) {
            logger.error("验证码错误++++++++", code);
            return ApiResult.fail("验证码错误");
        }
        //判断邀请码
        QueryWrapper<ClyjUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("invite_code", inviteCode);
        List<ClyjUser> list = clyjUserMapper.selectList(queryWrapper);

        if (list.size() == 0) {
            logger.error("邀请码错误++++++++", inviteCode);
            return ApiResult.fail("邀请码错误");
        }
        //判断是否已注册
        QueryWrapper<ClyjUser> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("phone", phone);
        ClyjUser clyjUser1 = this.clyjUserMapper.selectOne(queryWrapper1);
        if (clyjUser1 != null) {
            return ApiResult.fail("该手机号已注册");
        } else {
            String userPId = list.get(0).getUserId();
            Integer userPLevel = list.get(0).getLevel();
            clyjUser.setPhone(phone);
            clyjUser.setPassword(passwordEncoder().encode(pwd));
            return this.customerService.customerRegister(clyjUser, userPId, userPLevel, request);
        }


    }

    /**
     * 根据注册手机号查询是否已注册
     *
     * @param params
     * @return
     */
    @RequestMapping(value = "/isName")
    @ResponseBody
    public ApiResult isName(@RequestBody JSONObject params) {
        String phone = params.getString("phone");
        if (StringUtils.isEmpty(phone)) {
            logger.error("手机号为空++++++++", phone);
            return ApiResult.fail("手机号不能为空");
        } else {
            return this.customerService.isName(phone);
        }

    }

    /**
     * 查询登录用户信息
     *
     * @param params
     * @param request
     * @return
     */
    @RequestMapping("/login")
    @ResponseBody
    public ApiResult customerLogin(@RequestBody JSONObject params, HttpServletRequest request) {
        String phone = params.getString("phone");
        String code = params.getString("code");
        String pwd = params.getString("pwd");
        //判断传递过来的参数
        if (StringUtils.isEmpty(phone) && StringUtils.isEmpty(pwd)) {
            logger.error("用户名或密码为空++++++++", phone, pwd);
            return ApiResult.fail("用户名或密码为空");
        }

        if (!code.equals("12345")) {
            logger.error("验证码错误++++++++", code);
            return ApiResult.fail("验证码错误");
        }

        return this.customerService.customerLogin(phone, pwd, request);
    }


    /**
     * 微信登录
     *
     * @param request
     * @param response
     */
    @RequestMapping("/wxLogin")
    @ResponseBody
    public void wxLogin(HttpServletRequest request, HttpServletResponse response) {

        try {
            this.customerService.wxLogin(request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 登录回调
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping("/wxCallBack")
    @ResponseBody
    public String wxCallBack(HttpServletRequest request, HttpServletResponse response) throws Exception {

        return this.customerService.wxCallBack(request, response);
    }

    /**
     * 修改绑定手机号
     *
     * @param params
     * @return
     */
    @RequestMapping("/updatePhone")
    @ResponseBody
    public ApiResult updatePhone(@RequestBody JSONObject params) {
        String token = params.getString("token");
        if (token == null || "".equals(token)) {
            return ApiResult.fail("您好，你的账号已登陆失效，请重新登陆！");
        }
        ClyjUser clyjUser = tokenUtils.Itoken(token);
        if (clyjUser == null) {
            return ApiResult.fail("您好，你的账号已登陆失效，请重新登陆！");
        }
        String phone = params.getString("phone");
        String code = params.getString("code");
        String newphone = params.getString("newphone");
        String newcode = params.getString("newcode");
        if (StringUtils.isEmpty(phone) && StringUtils.isEmpty(code)) {
            logger.error("手机号或验证码为空++++++++++", phone, code);
            return ApiResult.fail("手机号或验证码为空");
        }
        if (!code.equals("12345")) {
            logger.error("验证码错误++++++++++", code);
            return ApiResult.fail("验证码错误");
        }
        if (StringUtils.isEmpty(newphone) && StringUtils.isEmpty(newcode)) {
            logger.error("手机号或验证码为空++++++++++", phone, code);
            return ApiResult.fail("手机号或验证码为空");
        }
        if (!newcode.equals("12345")) {
            logger.error("验证码错误++++++++++", code);
            return ApiResult.fail("验证码错误");
        }
        return this.customerService.updatePhone(phone, newphone);
    }

    /**
     * 修改登录密码
     *
     * @param params
     * @return
     */
    @RequestMapping("/updatePwd")
    @ResponseBody
    public ApiResult updatePwd(@RequestBody JSONObject params) {
        String token = params.getString("token");
        if (token == null || "".equals(token)) {
            return ApiResult.fail("您好，你的账号已登陆失效，请重新登陆！");
        }
        ClyjUser clyjUser = tokenUtils.Itoken(token);
        if (clyjUser == null) {
            return ApiResult.fail("您好，你的账号已登陆失效，请重新登陆！");
        }
        String phone = params.getString("phone");
        String code = params.getString("code");
        String pwd = params.getString("pwd");
        if (StringUtils.isEmpty(phone) && StringUtils.isEmpty(code)) {
            logger.error("手机号或验证码为空++++++++++", phone, code);
            return ApiResult.fail("手机号或验证码为空");
        }
        if (!code.equals("12345")) {
            logger.error("验证码错误++++++++++", code);
            return ApiResult.fail("验证码错误");
        }
        return this.customerService.updatePwd(phone, pwd);
    }

    /**
     * 修改支付密码
     *
     * @param params
     * @return
     */
    @RequestMapping("/updatePaypwd")
    @ResponseBody
    public ApiResult updatePaypwd(@RequestBody JSONObject params) {
        String token = params.getString("token");
        if (token == null || "".equals(token)) {
            return ApiResult.fail("您好，你的账号已登陆失效，请重新登陆！");
        }
        ClyjUser clyjUser = tokenUtils.Itoken(token);
        if (clyjUser == null) {
            return ApiResult.fail("您好，你的账号已登陆失效，请重新登陆！");
        }
        String phone = params.getString("phone");
        String code = params.getString("code");
        String newpayPwd = params.getString("newpayPwd");
        if (StringUtils.isEmpty(phone) && StringUtils.isEmpty(code)) {
            logger.error("手机号或验证码为空++++++++++", phone, code);
            return ApiResult.fail("手机号或验证码为空");
        }
        if (!code.equals("12345")) {
            logger.error("验证码错误++++++++++", code);
            return ApiResult.fail("验证码错误");
        }
        return this.customerService.updatePaypwd(phone, newpayPwd);
    }

    /**
     * 设置支付密码
     *
     * @param params
     * @return
     */
    @RequestMapping("/setPayPwd")
    @ResponseBody
    public ApiResult setPayPwd(@RequestBody JSONObject params) {
        String token = params.getString("token");
        if (token == null || "".equals(token)) {
            return ApiResult.fail("您好，你的账号已登陆失效，请重新登陆！");
        }
        ClyjUser clyjUser = tokenUtils.Itoken(token);
        if (clyjUser == null) {
            return ApiResult.fail("您好，你的账号已登陆失效，请重新登陆！");
        }
        String phone = params.getString("phone");
        String code = params.getString("code");
        String payPwd = params.getString("payPwd");

        if (StringUtils.isEmpty(phone) && StringUtils.isEmpty(code)) {
            logger.error("手机号或验证码为空+++++++++++", phone, code);
            return ApiResult.fail("手机号和验证码为空");
        }

        if (!code.equals("12345")) {
            logger.error("验证码错误+++++++++", code);
            return ApiResult.fail("验证码错误");
        }
        return this.customerService.setPayPwd(phone, payPwd);
    }


    /**
     * 修改头像和昵称
     *
     * @param params
     * @param icon
     * @return
     */
    @RequestMapping("/updateUserInfo")
    @ResponseBody
    public ApiResult updateUserInfo(@RequestBody JSONObject params, MultipartFile icon) {
        String token = params.getString("token");
        if (token == null || "".equals(token)) {
            return ApiResult.fail("您好，你的账号已登陆失效，请重新登陆！");
        }
        ClyjUser clyjUser = tokenUtils.Itoken(token);
        if (clyjUser == null) {
            return ApiResult.fail("您好，你的账号已登陆失效，请重新登陆！");
        }
        try {
            String username = params.getString("username");
            //根据手机号查询个人信息
            //查询重名
            ClyjUser u = this.customerService.getName(username);
            if (u != null) {
                throw new IllegalArgumentException(username + "已存在");
            }
            clyjUser.setUsername(username);
            if (icon != null) {
                //文档上传oss
                try {
                    String fileName = icon.getOriginalFilename();
                    String pox = fileName.substring(fileName.lastIndexOf(".") + 1);
                    InputStream inputStream = icon.getInputStream();
                    Map<String, Object> uploadByInputStream = OSSUtils.uploadByInputStream(inputStream, pox, "CLYJ/USER/");
                    clyjUser.setPhoto(uploadByInputStream.get("path").toString());
                } catch (Exception e) {
                    e.printStackTrace();
                    return ApiResult.fail("图片上传错误"+e.getMessage());
                }
            }
            boolean b = this.customerService.updateById(clyjUser);
            logger.error("修改成功");
            return ApiResult.success(b);
        } catch (Exception e) {
            logger.error("修改失败");
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 个人信息
     *
     * @param params
     * @return
     */
    @RequestMapping("/perInformation")
    @ResponseBody
    protected ApiResult perInformation(@RequestBody JSONObject params, HttpServletRequest request) {
        String token = params.getString("token");
        if (token == null || "".equals(token)) {
            return ApiResult.fail("您好，你的账号已登陆失效，请重新登陆！");
        }
        ClyjUser clyjUser = tokenUtils.Itoken(token);
        if (clyjUser == null) {
            return ApiResult.fail("您好，你的账号已登陆失效，请重新登陆！");
        }
        return this.customerService.perInformation(token, request);
    }

    /**
     * 微信信息
     *
     * @param params
     * @return
     */
    @RequestMapping("/perInformations")
    @ResponseBody
    protected ApiResult perInformations(@RequestBody JSONObject params, HttpServletRequest request) {
        String token = params.getString("token");
        if (token == null || "".equals(token)) {
            return ApiResult.fail("token不存在");
        }
        return this.customerService.perInformations(token, request);
    }
    /**
     * 微信登录注册
     *
     * @param params
     * @return
     */
    @RequestMapping("/wxRegister")
    @ResponseBody
    protected ApiResult wxRegister(@RequestBody JSONObject params, HttpServletRequest request) {
        String token = UUID.randomUUID().toString();
        String code = params.getString("code");
        String phone = params.getString("phone");
        String inviteCode = params.getString("inviteCode");
        String openid = params.getString("openid");
        String icon = params.getString("icon");
        String pwd = params.getString("pwd");
        //判断参数
        if (StringUtils.isEmpty(phone) && StringUtils.isEmpty(pwd)) {
            logger.error("手机号和密码为空++++++++", phone, pwd);
            return ApiResult.fail("用户名或密码为空");
        }
        //判断验证码
        if (!code.equals("12345")) {
            logger.error("验证码错误", code);
            return ApiResult.fail("验证码错误");
        }
        //判断邀请码
        QueryWrapper<ClyjUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("invite_code", inviteCode);
        ClyjUser clyjUser = clyjUserMapper.selectOne(queryWrapper);
        String userPid=clyjUser.getUserId();
        if (clyjUser == null) {
            return ApiResult.fail("邀请码错误");
        }
        //判断是否已注册
        QueryWrapper<ClyjUser> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("phone", phone);
        ClyjUser clyjUser1 = this.clyjUserMapper.selectOne(queryWrapper1);
        //如果手机号已注册,该账号绑定微信号直接返回token
        if (clyjUser1 != null) {
            clyjUser1.setOpenid(openid);
            clyjUser1.setPhoto(icon);
            clyjUserMapper.updateById(clyjUser1);
            redisUtil.set(token, clyjUser1);
            return ApiResult.success(token);
        }
        return this.customerService.wxRegister(code, phone, inviteCode, openid, icon, token, pwd, userPid,request);
    }
}
